{% extends "sysadmin/base.html" %}
{% load seahub_tags i18n %}
{% block cur_users %}tab-cur{% endblock %}

{% block left_panel %}{{block.super}}
<form action="{% url 'user_search' %}" method="get" class="side-search-form">
    <input type="text" name="email" class="input" value="" placeholder="{% trans "Search users..." %}" />
</form>
{% endblock %}

{% block right_panel %}
<div class="tabnav ovhd">
    <ul class="tabnav-tabs fleft">
        <li class="tabnav-tab tabnav-tab-cur"><a href="{% url 'sys_useradmin' %}">{% trans "Database" %}</a></li>
        {% if have_ldap %}
        <li class="tabnav-tab"><a href="{% url 'sys_useradmin_ldap' %}">{% trans "LDAP" %}</a></li>
        <li class="tabnav-tab"><a href="{% url 'sys_useradmin_ldap_imported' %}">{% trans "LDAP(imported)" %}</a></li>
        {% endif %}
        {% if is_default_admin %}
        <li class="tabnav-tab"><a href="{% url 'sys_useradmin_admins' %}">{% trans "Admins" %}</a></li>
        {% endif %}
        {% if enable_user_plan %}
        <li class="tabnav-tab"><a href="{% url 'sys_useradmin' %}?filter=paid">Paid</a></li>
        {% endif %}
    </ul>

    <div class="js-op-for-all fright">
        <button id="import-users-from-excel-btn">{% trans "Import users" %}</button>
        <button id="add-user-btn">{% trans "Add user" %}</button>
        <button id="export-excel">{% trans "Export Excel" %}</button>
    </div>
    <div class="js-op-for-selected fright hide">
        <button id="set-quota-btn">{% trans "Set quota" %}</button>
        {% if show_institution %}
        <button id="set-institution-btn">{% trans "Set institution" %}</button>
        {% endif %}
        <button id="delete-users-btn">{% trans "Delete users" %}</button>
    </div>
</div>

<form id="add-user-form" action="" method="post" class="hide">{% csrf_token %}
    <h3>{% trans "Add user" %}</h3>
    <label for="id_email">{% trans "Email" %}</label><br />
    <input type="text" name="email" id="id_email" class="input" /><br />

    <label for="id_name">{% trans "Name(optional)" %}</label><br />
    <input type="text" name="name" id="id_name" class="input" /><br />

    {% if is_pro %}
    <label>{% trans "Role"%}</label><span class="icon-question-sign" title="{% trans "You can also add a user as a guest, who will not be allowed to create libraries and groups." %}" style="color:#666; margin-left:3px;"></span>
    <select name="role" class="w100">
        <option value={{default_user}} selected="selected">{% trans "Default"%}</option>
        <option value={{guest_user}}>{% trans "Guest"%}</option>
        {% for role in extra_user_roles %}
            <option value={{role}}>{{ role }}</option>
        {% endfor %}
    </select><br />
    {% endif %}
    <label for="id_password1">{% trans "Password" %}</label>
    <div class="passwd-wrapper">
        <input type="password" name="password1" id="id_password1" class="passwd input" />
        <span title="{% trans "Show" %}" class="icon-eye show-or-hide-password cspt"></span>
        <span title="{% trans "Generate a random password" %}" class="icon-magic generate-random-password cspt"></span>
    </div>
    <label for="id_password2">{% trans "Confirm Password" %}</label><br />
    <input type="password" name="password2" id="id_password2" class="input" /><br />
    <p class="error hide"></p>
    <button type="submit" class="submit">{% trans "Submit" %}</button>
</form>

<form id="upload-excel-form" class="hide" enctype="multipart/form-data" method="post" action="{% url 'batch_add_user' %}">{% csrf_token %}
    <h3>{% trans "Import users from a .xlsx file" %}</h3>
    <a href="#" id="excel-example">{% trans "Download an example file" %}</a>
    <br />
    <input type="file" name="file" />
    <br />
    <p class="error hide">{% trans "Please choose a .xlsx file." %}</p>
    <button type="submit" class="submit">{% trans "Submit" %}</button>
</form>

{% with is_admin_page=False %}
{% include "sysadmin/useradmin_table.html" %}
{% endwith %}
{% include "snippets/admin_paginator.html" %}

<div id="activate-msg" class="hide">
    <p>{% trans "Activating..., please wait" %}</p>
</div>

{% if show_institution %}
<form class="hide" id="batch-set-institution-form" method="" action="">
    <h3>{% trans "Set institution" %}</h3>
    <select name="institution" class="w100">
        <option value=""></option>
        {% for inst in institutions %}
            <option value="{{inst}}">{{inst}}</option>
        {% endfor %}
    </select>
    <p class="error hide"></p>
    <button type="submit" class="submit">{% trans "Submit" %}</button>
</form>
{% endif %}
{% endblock %}
{% block extra_script %}
<script type="text/javascript">
$('#add-user-btn').on('click', function() {
    $('#add-user-form').modal();
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
});
$('#add-user-form .show-or-hide-password').on('click', function() {
    var icon = $(this),
        passwd_input = $('input[name=password1], input[name=password2]', $('#add-user-form'));
    icon.toggleClass('icon-eye icon-eye-slash');
    if (icon.hasClass('icon-eye')) {
        icon.attr('title', "{% trans "Show" %}");
        passwd_input.prop('type', 'password');
    } else {
        icon.attr('title', "{% trans "Hide" %}");
        passwd_input.prop('type', 'text');
    }
});
$('#add-user-form .generate-random-password').on('click', function() {
    var form = $('#add-user-form');
    var random_password = '';
    var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789';
    for (var i = 0; i < 8; i++) {
        random_password += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    $('input[name=password1], input[name=password2]', form).prop('type', 'text').val(random_password);
    $('.show-or-hide-password', form)
    .attr('title', "{% trans "Hide" %}")
    .removeClass('icon-eye').addClass('icon-eye-slash');
});
$('#add-user-form').on('submit', function() {
    var form = $(this),
        form_id = $(this).attr('id'),
        email = $.trim(form.children('[name="email"]').val()),
        name = $.trim($('[name="name"]', form).val()),
        {% if is_pro %}
        role = $('select[name="role"]', form).val(),
        {% endif %}
        pwd1 = $.trim(form.find('[name="password1"]').val()),
        pwd2 = $.trim(form.children('[name="password2"]').val());

    if (!email) {
        apply_form_error(form_id, "{% trans "Email cannot be blank" %}");
        return false;
    }
    if (!pwd1) {
        apply_form_error(form_id, "{% trans "Password cannot be blank" %}");
        return false;
    } 
    if (!pwd2) {
        apply_form_error(form_id, "{% trans "Please enter the password again" %}");
        return false;
    } 
    if (pwd1 != pwd2) {
        apply_form_error(form_id, "{% trans "Passwords do not match" %}");
        return false;
    } 

    var submit_btn = $(this).find('[type="submit"]');
    disable(submit_btn);
    $.ajax({
        url: '{% url 'api-v2.1-admin-users' %}',
        type: 'POST',
        datatype: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {
            'email': email,
            'name': name,
            {% if is_pro %}
            'role': role,
            {% endif %}
            'password': pwd1,
            'is_active': true
        },
        success: function(data) {
            let email = data.email
            let msg = "";
            {% if is_email_configured %}
                {% if send_email_on_adding_system_member %}
                    msg = "{% trans "Successfully added user {placeholder}. An email notification has been sent." %}".replace('{placeholder}', email)
                {% else %}
                    msg = "{% trans "Successfully added user {placeholder}." %}".replace('{placeholder}', email)
                {% endif %}
            {% else %}
                msg = "{% trans "Successfully added user {placeholder}. But email notification can not be sent, because Email service is not properly configured." %}".replace('{placeholder}', email)
            {% endif %}
            if (msg != "") {
                localStorage.setItem("add_user_msg",msg);
            }
            window.location.reload();
        },  
        error: function(xhr, textStatus, errorThrown) {
            var error_msg = prepareAjaxErrorMsg(xhr);
            apply_form_error(form_id, error_msg);
            enable(submit_btn);
        }
    });
    return false;
});

$(document).ready(function(){
    if (localStorage.getItem("add_user_msg")) {
        feedback(localStorage.getItem("add_user_msg"), 'success');
        localStorage.removeItem("add_user_msg");
    }
});

$('#import-users-from-excel-btn').on('click', function () {
    $('#upload-excel-form').modal();
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
});
$("#excel-example").on('click', function() {
    location.href = "{% url 'batch_add_user_example' %}";
    return false;
});
$('#upload-excel-form').on('submit', function() {
    var form = $(this);
    if (!$('[name=file]', form).val()) {
        $('.error', form).removeClass('hide');
        return false;
    }
});
$("#export-excel").on('click', function() {
    location.href = "{% url 'sys_useradmin_export_excel' %}";
});
{% include "sysadmin/useradmin_js.html" %}
</script>
{% endblock %}
